package com.newegg.app.qec.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.newegg.app.qec.R;
import com.newegg.app.qec.util.APIMethod;
import com.newegg.app.qec.util.BaseActivity;
import com.newegg.app.qec.util.Constants;
import com.newegg.app.qec.util.JudgeUtil;
import com.newegg.app.qec.util.MyApplication;
import com.newegg.app.qec.util.NetworkUtil;
import com.newegg.app.qec.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Allen on 2017/12/7.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private ImageView back;
    private TextView name;
    private EditText phone_number;
    private EditText yan_zheng_ma;
    private TextView huo_qu_register;
    private TextView next;
    private ImageView agreement_iv;
    private TextView agreement_tv;
    private LinearLayout agreement_lin;
    //标记从哪个功能跳转当前页面
    private String tag;
    //记录是否同意协议
    private boolean lean = true;

    private Timer timer;// 计时器
    private int jishi = 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yanzheng);
        back = (ImageView) findViewById(R.id.img_back);
        name = (TextView) findViewById(R.id.title_name);
        phone_number = (EditText) findViewById(R.id.phone_number);
        yan_zheng_ma = (EditText) findViewById(R.id.yan_zheng_ma);
        huo_qu_register = (TextView) findViewById(R.id.huo_qu_register);
        next = (TextView) findViewById(R.id.next);
        agreement_iv = (ImageView) findViewById(R.id.agreement_iv);
        agreement_tv = (TextView) findViewById(R.id.agreement_tv);
        agreement_lin = (LinearLayout) findViewById(R.id.agreement_lin);

        back.setOnClickListener(this);
        next.setOnClickListener(this);
        agreement_iv.setOnClickListener(this);
        huo_qu_register.setOnClickListener(this);

        tag = getIntent().getStringExtra("tag");
        if (TextUtils.equals(tag, "register")) {
            name.setText("注册账号");
            agreement_lin.setVisibility(View.VISIBLE);
            agreement_tv.setText(Html.fromHtml("我已阅读并接受<font color='#de0d24'><u>版权声明</u></font>和<font color='#de0d24'><u>隐私条款</u></font>"));
        } else if (TextUtils.equals(tag, "forget")) {
            name.setText("忘记密码");

        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.agreement_iv:
                if (lean) {
                    lean = false;
                    agreement_iv.setImageResource(R.mipmap.login_xieyi1);
                    next.setBackgroundResource(R.drawable.button_gray);
                    next.setTextColor(RegisterActivity.this.getResources().getColor(R.color.black));
                    next.setClickable(false);
                } else {
                    lean = true;
                    agreement_iv.setImageResource(R.mipmap.login_xieyi2);
                    next.setBackgroundResource(R.drawable.button_red);
                    next.setTextColor(RegisterActivity.this.getResources().getColor(R.color.white));
                    next.setClickable(true);
                }
                break;

            case R.id.huo_qu_register:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String number = phone_number.getText().toString();
                if (TextUtils.isEmpty(number)) {
                    ToastUtil.showToast(RegisterActivity.this, "手机号不能为空");
                } else {
                    if (NetworkUtil.isNetworkAvailable(RegisterActivity.this)) {
                        if (JudgeUtil.isMobile(number)) {
                            huoQuYanZheng(number);
                        } else {
                            ToastUtil.showToast(RegisterActivity.this, "手机号码不合法");
                        }

                    } else {
                        ToastUtil.showToast(RegisterActivity.this, "请检查您的网络状态");
                    }

                }
                break;
            case R.id.next:
                if (TextUtils.equals(tag, "register")) {
                    String phonenumber = phone_number.getText().toString();
                    String yzm = yan_zheng_ma.getText().toString();
                    if (!TextUtils.isEmpty(phonenumber) && !TextUtils.isEmpty(yzm)) {
                        if (NetworkUtil.isNetworkAvailable(RegisterActivity.this)) {
                            yanZheng(phonenumber, yzm);
                        } else {
                            ToastUtil.showToast(RegisterActivity.this, "请检查您的网络状态");
                        }
                        //保存电话号码
                        Constants.setPhoneNumberByName(RegisterActivity.this, "phonenumber", phonenumber);
                    } else {
                        ToastUtil.showToast(RegisterActivity.this, "手机号和验证码不能为空");
                    }
                } else if (TextUtils.equals(tag, "forget")) {
//                    intent.setClass(RegisterActivity.this, ResetPassWordActicity.class);
//                    startActivity(intent);
                    String phonenumber = phone_number.getText().toString();
                    String yzm = yan_zheng_ma.getText().toString();
                    if (!TextUtils.isEmpty(phonenumber) && !TextUtils.isEmpty(yzm)) {
                        if (NetworkUtil.isNetworkAvailable(RegisterActivity.this)) {
                            yanZheng(phonenumber, yzm);
                        } else {
                            ToastUtil.showToast(RegisterActivity.this, "请检查您的网络状态");
                        }
                        //保存电话号码
                        Constants.setPhoneNumberByName(RegisterActivity.this, "phonenumber", phonenumber);
                    } else {
                        ToastUtil.showToast(RegisterActivity.this, "手机号和验证码不能为空");
                    }
                }
                break;
        }
    }

    //验证token和验证码是否正确
    private void yanZheng(final String phonenumber, String yzm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RequestBody formBody = new FormBody.Builder().add("token", Constants.getRegisterTokenByName(RegisterActivity.this, "registertoken")).
                            add("account", phonenumber).add("code", Constants.getRegisterCodeByName(RegisterActivity.this, "registercode")).build();
                    Request request = new Request.Builder().url(APIMethod.YanZhengYanZhengMa).put(formBody).build();
                    Response response = MyApplication.okHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    Log.i("yanzhengyanzhengma", code + "");
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler1.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler1.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    //获取验证码
    private void huoQuYanZheng(final String number) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    String str = "";
//                    if (TextUtils.equals(tag, "register")) {
//                         str = "register";
//
//                    } else if (TextUtils.equals(tag, "forget")) {
//                         str = "forgetpassword";
//                    }
                    RequestBody formBody = new FormBody.Builder().add("function", "register").add("mobile", number).build();
                    Request request = new Request.Builder().url(APIMethod.HuoQuYanZhengMa).post(formBody).build();
                    Response response = MyApplication.okHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    Log.i("yanzhengma", bodys);
                    Log.i("yanzhengma", code + "");
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                        JSONObject jsonObject = new JSONObject(bodys);
                        String token = jsonObject.optString("token");
                        String tokencode = jsonObject.optString("code");
                        Log.i("ddddd", tokencode + "");
                        //保存验证码的token
                        Constants.setRegisterTokenByName(RegisterActivity.this, "registertoken", token);
                        //保存验证码
                        Constants.setRegisterCodeByName(RegisterActivity.this, "registercode", tokencode);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    //获取验证码的handler
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    jishi = 60;
                    huo_qu_register.setEnabled(false);
                    yan_zheng_ma.setInputType(InputType.TYPE_NULL);
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            timerHandler.sendEmptyMessage(jishi--);
                        }
                    }, 0, 1000);
                    huo_qu_register.setBackgroundResource(R.color.bei_jing);
                    huo_qu_register.setTextColor(RegisterActivity.this.getResources().getColor(R.color.black));
                    if (Constants.getRegisterCodeByName(RegisterActivity.this, "registercode")!=null){
                        yan_zheng_ma.setText(Constants.getRegisterCodeByName(RegisterActivity.this, "registercode"));
                        ToastUtil.showToast(RegisterActivity.this, "验证码已发送到你的手机，请注意查收！");
                    }else {
                        ToastUtil.showToast(RegisterActivity.this, "获取验证码失败，请稍后重新获取！");
                    }

                    break;
                case 1:
                    ToastUtil.showToast(RegisterActivity.this, "获取验证码失败，请稍后重新获取！");

                    break;
            }
        }
    };

    //验证验证码的handler
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Intent intent = new Intent();
                    intent.setClass(RegisterActivity.this, SetPassWordActicity.class);
                    startActivity(intent);
                    RegisterActivity.this.finish();
                    break;
                case 1:
                    ToastUtil.showToast(RegisterActivity.this, "验证码不正确，请重新获取");
                    break;
            }
        }
    };

    //验证码计时器
    private Handler timerHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                huo_qu_register.setEnabled(true);
                huo_qu_register.setText("获取验证码");
                huo_qu_register.setBackgroundResource(R.color.red);
                huo_qu_register.setTextColor(RegisterActivity.this.getResources().getColor(R.color.white));
                timer.cancel();
            } else {
                huo_qu_register.setText(msg.what + "秒后重发");
            }
        }
    };
}
